package com.king.hpeproject.constant;

import com.king.hpeproject.exception.BusinessException;
import lombok.Getter;
import lombok.Setter;

import java.util.List;

@Getter
@Setter
public class RequestContext {
    private static final ThreadLocal<RequestContext> contextHolder = ThreadLocal.withInitial(RequestContext::new);

    /**
     * 组织id
     */
    private Long orgId;

    /**
     * 项目id列表
     */
    private List<Long> projectIds;

    /**
     * 用户id
     */
    private Long userId;

    /**
     * 用户名
     */
    private String userName;

    /**
     * 是否总公司
     */
    private Boolean isHead = false;

    // 私有构造，防止外部直接实例化
    private RequestContext() {}

    /**
     * 获取当前线程的 RequestContext
     */
    public static RequestContext getCurrentContext() {
        return contextHolder.get();
    }

    public String getUsername() {
        return userName != null ? userName : CommonConstant.UNKNOWN.getCode();
    }

    /**
     * 根据用途获取组织id
     *
     * @param isQueryConditions true：作为查询条件，false：非查询用途，例如填充
     * @return 组织id
     */
    public Long getOrgId(boolean... isQueryConditions) {
        if ((isQueryConditions == null || isQueryConditions.length == 0 || isQueryConditions[0]) && isHead) {
            return null;
        }
        return orgId;
    }

    public Long getProjectId() {
        if (projectIds.size() > 1) {
            throw new BusinessException(BusinessExceptionConstant.OPERATION_NO_SPECIFIED_PROJECT_ERROR);
        }
        return projectIds.get(0);
    }

    /**
     * 清除当前线程的 RequestContext，防止内存泄漏（重要！）
     */
    public static void clear() {
        contextHolder.remove();
    }
}